<?php

/**
 * 款项设置
 *
 * @package		Hooloo framework
 * @author 		Bill
 * @copyright 	Hooloo Co.,Ltd
 * @version		1.0
 * @release		2017.05.08
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Userbill extends Controller{
	public function __construct(){
		parent::__construct();
	}

	/**
     * 资金明细
	 * @param	int		$aid			代理上ID
     * @param	int		$demo_account 	帐号类型
     * @param	int		$start_time 	开始时间
     * @param	int		$end_time 		结束时间
     * @param	string	$username 		用户名
     * @param	array	$result 		返回结果
     */
	public function index($demo_account = 0, $start_time = 0, $end_time = 0, $username = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		$where = " where a.aid = $aid";
		
		//帐号类型
		$demo_account = (int)$demo_account;
		if($demo_account == 0){
			$where .= " and b.demo_account = 0";
		} elseif($demo_account == 1){
			$where .= " and b.demo_account = 1";
		} else{
			$demo_account = 2;
		}
		
		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d"); 
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		$where .= " and a.addtime >= '".$start_time."' and a.addtime <= '".$end_time . " 23:59:59"."'";
		
		//搜索条件
		if($username){
			$where .= " and (b.username like '%$username%')";
		} else{
			$username = 0;
		}
		
		//数据分页
		$p = (int)$p <= 0 ? 1 : (int)$p;
		$pize = 15;
		$start = ($p - 1) * $pize;

		//查询总数
		$sql = "select count(*) as c from log_bill a inner join user b on a.uid = b.id " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//分页查询
		$sql = "select a.*, b.demo_account, b.agent_name, b.username from log_bill a inner join user b on a.uid = b.id " . $where . " order by a.id desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
	
		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/" . $demo_account . "/" . $start_time . "/". $end_time . "/". $username . "/";
		$page = page_format($total, $pize, $p, $url);

		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		
		$this->assign("demo_account", $demo_account);
		$this->assign("start_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("username", $username);
		$this->display();
	}
	
	/**
     * 用户账单
	 * @param	int		$aid			代理上ID
	 * @param	int		$sid			员工ID
     * @param	int		$demo_account 	帐号类型
     * @param	int		$start_time 	开始时间
     * @param	int		$end_time 		结束时间
     * @param	string	$username 		用户名
     * @param	array	$result 		返回结果
     */
	public function logs($sid = 0, $demo_account = 0, $start_time = 0, $end_time = 0, $username = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		$where = " a.aid = $aid";
		
		//指定员工
		$sid = (int)$sid;
		if($sid == 0){
			$where .= " and b.sid > 0";
		} else{
			$where .= " and b.sid = $sid";
		}
		
		//帐号类型
		$demo_account = (int)$demo_account;
		if($demo_account == 0){
			$where .= " and b.demo_account = 0";
		} elseif($demo_account == 1){
			$where .= " and b.demo_account = 1";
		} else{
			$demo_account = 2;
		}

		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d");
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		
		//搜索条件
		if($username){
			$where .= " and (b.username like '%$username%')";
		} else{
			$username = 0;
		}
		
		//查询记录 - 交易总额(买入股票)
		$sql = "SELECT FROM_UNIXTIME(a.bull_time, '%Y%m%d') fdate, a.uid, b.agent_name, b.staff_name, b.username, b.realname, sum(a.bull_money) amount, sum(a.bull_cost_money) bull_cost_money  FROM `stock_bull` a inner join `user` b on a.uid = b.id where " . $where . " and a.bull_time >= '".strtotime($start_time)."' and a.bull_time <= '".strtotime($end_time . " 23:59:59")."' GROUP BY fdate, a.uid;";
		$bull = $this->db->query($sql)->result_array();
		$uid1 = array_column($bull, null, "uid");

		//查询记录 - 交易总额(卖出股票)
		$sql = "SELECT FROM_UNIXTIME(a.sell_time, '%Y%m%d') fdate, a.uid, b.agent_name, b.staff_name, b.username, b.realname, sum(a.sell_money) amount, sum(a.cost_money) sell_cost_money, sum(a.save_money) save_money, sum(a.stamp_money) stamp_money, sum(a.manage_money) manage_money, sum(a.gain) gain FROM `stock_sell` a inner join `user` b on a.uid = b.id where " . $where . "  and a.sell_time >= '".strtotime($start_time)."' and a.sell_time <= '".strtotime($end_time . " 23:59:59")."' GROUP BY fdate, a.uid;";
		$sell = $this->db->query($sql)->result_array();
		$uid2 = array_column($sell, null, "uid");

		//格式化数据
		$all_amount = $all_fee = $all_save = $all_stamp = $all_manage = $all_gain = 0;
		$uid = array_merge(array_keys($uid1), array_keys($uid2));
		sort($uid);
		$uid = array_unique($uid);
        $list = array();
		foreach ($uid as $key => $val) {
			$list[$key]["uid"] = $val;
			$list[$key]["fdate"] = isset($uid1[$val]["fdate"]) ? $uid1[$val]["fdate"] : $uid2[$val]["fdate"];
			$list[$key]["agent_name"] = isset($uid1[$val]["agent_name"]) ? $uid1[$val]["agent_name"] : $uid2[$val]["agent_name"];
			$list[$key]["staff_name"] = isset($uid1[$val]["staff_name"]) ? $uid1[$val]["staff_name"] : $uid2[$val]["staff_name"];
			$list[$key]["username"] = isset($uid1[$val]["username"]) ? $uid1[$val]["username"] : $uid2[$val]["username"];
			$list[$key]["realname"] = isset($uid1[$val]["realname"]) ? $uid1[$val]["realname"] : $uid2[$val]["realname"];
			
			//计算交易量
			$amount1 = isset($uid1[$val]["amount"]) ? $uid1[$val]["amount"] : 0;
			$amount2 = isset($uid2[$val]["amount"]) ? $uid2[$val]["amount"] : 0;
			$all_amount += $list[$key]["amount"] = $amount1 + $amount2;
			
			//计算手续费
			$cost_money1 = isset($uid1[$val]["bull_cost_money"]) ? $uid1[$val]["bull_cost_money"] : 0;
			$cost_money2 = isset($uid2[$val]["sell_cost_money"]) ? $uid2[$val]["sell_cost_money"] : 0;
			$all_fee += $list[$key]["fee"] = $cost_money1 + $cost_money2;

			//计算其他费用
			$all_gain += $list[$key]["gain"] = isset($uid2[$val]["gain"]) ? $uid2[$val]["gain"] : 0;
			$all_save += $list[$key]["save"] = isset($uid2[$val]["save_money"]) ? $uid2[$val]["save_money"] : 0;
			$all_stamp += $list[$key]["stamp"] = isset($uid2[$val]["stamp_money"]) ? $uid2[$val]["stamp_money"] : 0;
			$all_manage += $list[$key]["manage"] = isset($uid2[$val]["manage_money"]) ? $uid2[$val]["manage_money"] : 0;
		}
		
		//数据分页
		$p = (int)$p <= 0 ? 1 : (int)$p;
		$size = 15;
		$start = ($p - 1) * $size;

		//查询总数
		$total = count($list);

		//分页查询
		$list = array_slice($list, $start, $size);

		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/" . $sid . "/" . $demo_account . "/". $start_time . "/". $end_time . "/". $username . "/";
		$page = page_format($total, $size, $p, $url);
		
		//查询所属员工
		if ($aid > 0) {
			$sql = "select * from agent_staff where aid = $aid";
			$staff = $this->db->query($sql)->result_array();
		} else {
			$staff = array();
		}
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("staff",$staff);
		$this->assign("page", $page);
		$this->assign("total", $total);
		
		$this->assign("all_amount", $all_amount);
		$this->assign("all_fee", $all_fee);
		$this->assign("all_save", $all_save);
		$this->assign("all_stamp", $all_stamp);
		$this->assign("all_manage", $all_manage);
		$this->assign("all_gain", $all_gain);
		
		$this->assign("aid", $aid);
		$this->assign("sid", $sid);
		$this->assign("demo_account", $demo_account);
		$this->assign("start_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("username", $username);
		$this->display();
	}
	
	/**
     * 手动入金
	 * @param	int		$type		充值类型
     * @param	int		$uid 		用户id
     * @param	int		$aid 		代理商id
     * @param	int		$money 		充值金额
     * @param	remark	$remark 	备注
     * @param	array	$result 	返回结果
     */
	public function charge(){
		if(IS_POST){
			//接收参数
			$type =  isset($_POST["type"]) ? (int)$_POST["type"] : 0;
			$uid =  isset($_POST["uid"]) ? (int)$_POST["uid"] : 0;
			$money =  isset($_POST["money"]) ? (int)$_POST["money"] : 0;
			
			//设置参数
			$add_time =  time();
			$aid = $_SESSION["agent"]["id"];
			if($aid <= 0) ajax_return(0, "请选择代理商");
			if($uid <= 0) ajax_return(0, "请选择用户");
			if($money <= 0) ajax_return(0, "请输入发生金额，必须为正数");

			//校验用户
			$sql = "select id from user where id = $uid and aid = $aid";
			$res = $this->db->query($sql)->row_array();
			if (! $res) ajax_return(0, "用户不存在");
			
			//开启事务
			$this->db->trans_begin();
			
			//写入资金明细
			$sql = "insert into log_charge (uid, aid, money) values ($uid, $aid, $money)";
			$this->db->query($sql);
			$res =$this->db->insert_id();

			if(! $res){
				//事务回滚
				$this->db->trans_rollback();
				ajax_return(0, "入金失败");
			} else{
				//更新账户
				$result = common_user($uid, $money, $money * 10, 0, "用户入金:" . $money . "元");
				if (! $result) {
					//事务回滚
					$this->db->trans_rollback();
					ajax_return(0, "入金失败");
				}
				
				//事务提交
				$this->db->trans_commit();
				
				//返回结果
				ajax_return(1, "入金成功");
			}
		}
		
		//查询所有用户
		$aid = $_SESSION["agent"]["id"];
		$sql = "select * from user where aid = $aid";
		$user = $this->db->query($sql)->result_array();
		
		$this->assign("user", $user);
		$this->display();
	}
	
	/**
     * 充值记录
     */
	public function charge_log($username = 0, $start_time = 0, $end_time = 0, $p = 1) {
		//接收参数
		$aid = $_SESSION["agent"]["id"];
		$p = intval($p);
		$username = urldecode(sql_format($username));
		
		//存在代理
		$where = "where 1=1";
		$aid = (int)$aid <= 0 ? 0 : (int)$aid;
		if($aid){
			$where .= " AND a.aid = '$aid'";
		}

		//用户搜索
		if($username){
			$where .= " AND b.username like '%$username%'";
		} else {
			$username = 0;
		}
		
		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d");
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		$where .= " and a.addtime >= '" . $start_time . "' and a.addtime <= '" . ($end_time . " 23:59:59") . "'";
		
		//数据分页
		$p = (int)$p <= 0 ? 1 : (int)$p;
		$pize = 15;
		$start = ($p - 1) * $pize;
		
		//统计总数
		$sql = "select count(*) as c from log_charge a inner join user b on a.uid = b.id " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];

		//分页查询
		$sql = "select a.*, b.username from log_charge a inner join user b on a.uid = b.id " . $where . " order by a.id DESC limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/". $username . "/" . $start_time . "/" . $end_time . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//格式化数据
		foreach ($list as $key => $val) {
			$list[$key]["money"] = number_format($val["money"], 2);
		}
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		$this->assign("start_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("username", $username);
		$this->display();
	}
	
	/**
     * 撤销充值
     */
	public function charge_cancel($id = 0) {
		if (IS_AJAX) {
			$id = intval($id);
			//校验参数
			if (0 >= $id) ajax_return(0, "参数有误");
			$aid = $_SESSION["agent"]["id"];

			//查询记录
			$sql = "select * from log_charge where id = $id and aid = $aid and status = 0";
			$row = $this->db->query($sql)->row_array();
			if (!$row) ajax_return(0, "非法请求");

			//开启事务
			$this->db->trans_begin();
			
			//撤销充值
			$money = $row["money"];
			//更新账户
			$result = common_user($row["uid"], -$money, -$money * 10, 0, "撤销充值:" . $money . "元");
			if (! $result) {
				//事务回滚
				$this->db->trans_rollback();
				ajax_return(0, "撤销失败");
			}
			
			//更新状态
			$sql = "update log_charge set status = 1, uptime = CURRENT_TIMESTAMP where id = $id and aid = $aid and status = 0";
			$this->db->query($sql);
			
			//事务提交
			$this->db->trans_commit();
			
			//返回结果
			ajax_return(1, "撤销成功");
		}
	}
	
	/**
     * 删除明细
	 * @param	int		$id			明细记录id
     * @param	array	$result 	返回结果
     */
	public function delete($id = 0) {
		if (IS_POST) {
			//校验参数
			if (0 >= $id) {
				ajax_return(0, "参数有误");
			}
			
			$status = isset($_POST["status"]) ? intval($_POST["status"]) : 1;//0-正常，1-删除，2-撤销
			if ($status < 1 || $status > 2) $status = 1;
			
			//指定代理商
			$aid = $_SESSION["agent"]["id"];
			
			if ($status == 2) {
				//查询资金
				$sql = "select money, uid, aid from user_bill where id = $id and aid = $aid";
				$res = $this->db->query($sql)->row_array();
				$money = $res["money"];
				$uid = $res["uid"];
				$aid = $res["aid"];
				
				//减去资金
				$sql = "update user set finance = finance - $money , amount  = amount - ($money * 10) where id = $uid and aid = $aid";
				$this->db->query($sql);
				
				$msg = "记录已强制撤销";
			} else {
				$msg = "记录已删除";
			}
			
			//删除明细
			$sql = "update user_bill set status = $status where id = $id and aid = $aid";
			$this->db->query($sql);
			
			//返回结果集
			ajax_return(1, $msg);
		}
	}
}
